package demo.util;

import redis.clients.jedis.Jedis;

import java.util.Random;


public class MyRedisLock {

    private Jedis jedis;

    private String lockKey;

    private String value;

    private static final Integer DEFAULT_TIMEOUT = 30;

    private static final String SUFFIX = ":lock";

    public MyRedisLock(Jedis jedis) {
        this.jedis = jedis;
    }

    public boolean acquire(String key, long time) throws InterruptedException {
        Long outdatedTime = System.currentTimeMillis() + time;
        lockKey = key + SUFFIX;
        while (true) {
            if (System.currentTimeMillis() >= outdatedTime) {
                return false;
            }
            value = String.valueOf(System.currentTimeMillis() + DEFAULT_TIMEOUT);
            if (jedis.setnx(lockKey, value) == 1) {
                jedis.expire(lockKey, DEFAULT_TIMEOUT);
                return true;
            }
        }
    }

    public boolean check() {
        return  jedis.exists(lockKey)
                && jedis.get(lockKey).equals(value);
    }

    public void release() {
        if (check()) {
            jedis.del(lockKey);
        }
    }
}
